import json
import requests

DEEPSEEK_API_KEY = 'sk-666bfc4035484c0fa399d8b83348b192'

class DeepseekChat:
    def __init__(self, api_key=DEEPSEEK_API_KEY, secret_key=''):
        self.api_key = api_key
        self.secret_key = secret_key
        self.access_token = None

    # 获取token
    def get_token(self):
        self.access_token = self.api_key
        return self.access_token

    # 调用模型
    def do_chat(self, message):
        if not self.access_token:
            self.get_token() 
        url = f"https://api.deepseek.com/chat/completions"
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': f'Bearer {self.access_token}'
        }
        payload = json.dumps({
            "model": "deepseek-reasoner",
            "messages": [
                {
                    "role": "user",
                    "content": message + "(注：如果用户输入有给出参考网址，那么回答时可搜索参考该网址的内容并在回答中体现)"
                }
            ],
            "stream": False
        })

        response = requests.request("POST", url, headers=headers, data=payload)
        
        try:
            content = json.loads(response.text)
        except (KeyError, json.JSONDecodeError) as e:
            print(f"Error decoding JSON from chat response: {e}")
            return {"error": "格式解析错误，请重试"}

        if 'choices' in content and len(content['choices']) > 0:
            if 'message' in content['choices'][0] and 'content' in content['choices'][0]['message']:
                result = content['choices'][0]['message']['content']
                return result
            else:
                print("Error: Response JSON structure is not as expected.")
                return {"error": "格式解析错误，请重试"}
        else:
            print("Error: Response JSON does not contain 'choices'.")
            return {"error": "格式解析错误，请重试"}

if __name__ == '__main__':
    chat_bot = DeepseekChat()
    response = chat_bot.do_chat("你好")
    print(response)
